package com.cap.dreamcircle.View;

import android.content.Intent;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.cap.dreamcircle.App.App;
import com.cap.dreamcircle.Base.BaseActivity;
import com.cap.dreamcircle.Consts.Constants;
import com.cap.dreamcircle.Model.Bean.AnonymousResponseBean;
import com.cap.dreamcircle.Model.Bean.BaseBean;
import com.cap.dreamcircle.Model.Bean.WechatAccessEntity;
import com.cap.dreamcircle.Model.Bean.WechatUserInfoEntity;
import com.cap.dreamcircle.Model.IExternalModel;
import com.cap.dreamcircle.Model.IUserModel;
import com.cap.dreamcircle.Model.Impl.ExternalModelImpl;
import com.cap.dreamcircle.Model.Impl.UserModelImpl;
import com.cap.dreamcircle.R;
import com.cap.dreamcircle.Utils.CommonSubscriber;
import com.cap.dreamcircle.Utils.DeviceUtils;
import com.cap.dreamcircle.Utils.DownloadUtils;
import com.cap.dreamcircle.Utils.KeyCounterUtils;
import com.cap.dreamcircle.Utils.MD5Utils;
import com.cap.dreamcircle.Utils.PreferenceUtils;
import com.cap.dreamcircle.Utils.RetrofitUploadFileParameterBuilder;
import com.cap.dreamcircle.Utils.ToastUtils;
import com.cap.dreamcircle.Utils.TransformUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;
import rx.Observable;
import rx.functions.Action0;
import rx.functions.Func1;

/**
 * Created by liucxu on 2017/7/11.
 */

public class DeviceRegisterActivity extends BaseActivity {

    @BindView(R.id.layout_wechat_login)
    LinearLayout layout_wechat_login;
    @BindView(R.id.layout_phone_login)
    LinearLayout layout_phone_login;


    private IUserModel userModel;

    private IExternalModel externalModel;

    private DownloadUtils downloadUtils;

    private IWXAPI api;

    private String wechatHeadImg = "";
    private String wechatNickName = "";
    private int wechatSex = -2;
    private String unionId = "";
    private File avasterFile;

    @Override
    public int getLayoutId() {
        return R.layout.activity_device_register;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        userModel = new UserModelImpl();
        externalModel = new ExternalModelImpl();
        downloadUtils = new DownloadUtils();
    }

    @Override
    public void setupData() {
        api = WXAPIFactory.createWXAPI(this, Constants.WEIXIN_APPID, false);
        api.registerApp(Constants.WEIXIN_APPID);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!(TextUtils.isEmpty(PreferenceUtils.GetUserToken()) || TextUtils.isEmpty(PreferenceUtils.GetUserId()))) {
            Intent intent = new Intent(DeviceRegisterActivity.this, MainActivity.class);
            startActivity(intent);
            App.GetInstance().finishActivity(DeviceRegisterActivity.this);
        } else if (!TextUtils.isEmpty(Constants.WECHAT_LOGIN_CODE)) {
            showProgress();
            doRequestWechatInfo();
        }
    }

    private void bytes2File(byte[] bytes) {
        try {
            String root = Environment.getExternalStorageDirectory().toString();
            File myDir = new File(root + "/dreamcircle");
            myDir.mkdirs();
            String fname = ((new Date()).getTime()) + ".png";
            avasterFile = new File(myDir, fname);
            if (avasterFile.exists()) avasterFile.delete();
            avasterFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(avasterFile);
            fos.write(bytes, 0, bytes.length);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doRequestWechatInfo() {
        String request_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constants.WEIXIN_APPID + "&secret=" + Constants.WEIXIN_APPSECRET + "&code=" + Constants.WECHAT_LOGIN_CODE + "&grant_type=authorization_code";
        externalModel.getExternalRequest(request_url).flatMap(new Func1<JsonObject, Observable<WechatAccessEntity>>() {
            @Override
            public Observable<WechatAccessEntity> call(JsonObject jsonObject) {
                String json_string = jsonObject.toString();
                WechatAccessEntity access = (new Gson()).fromJson(json_string, WechatAccessEntity.class);
                return Observable.just(access);
            }
        }).flatMap(new Func1<WechatAccessEntity, Observable<JsonObject>>() {
            @Override
            public Observable<JsonObject> call(WechatAccessEntity wechatAccessEntity) {
                String request_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + wechatAccessEntity.getAccess_token() + "&openid=" + wechatAccessEntity.getOpenid();
                return externalModel.getExternalRequest(request_info_url);
            }
        }).flatMap(new Func1<JsonObject, Observable<WechatUserInfoEntity>>() {
            @Override
            public Observable<WechatUserInfoEntity> call(JsonObject jsonObject) {
                String json_string = jsonObject.toString();
                WechatUserInfoEntity info = (new Gson()).fromJson(json_string, WechatUserInfoEntity.class);
                wechatHeadImg = info.getHeadimgurl();
                wechatNickName = info.getNickname();
                wechatSex = info.getSex();
                unionId = info.getUnionid();
//                unionId = System.currentTimeMillis()+"";
                return Observable.just(info);
            }
        }).flatMap(new Func1<WechatUserInfoEntity, Observable<byte[]>>() {
            @Override
            public Observable<byte[]> call(WechatUserInfoEntity wechatUserInfoEntity) {
                return downloadUtils.downloadIamge(wechatHeadImg);
            }
        }).flatMap(new Func1<byte[], Observable<AnonymousResponseBean>>() {
            @Override
            public Observable<AnonymousResponseBean> call(byte[] bytes) {
                bytes2File(bytes);
                String sex = "";
                if (wechatSex == 1) {
                    sex = "boy";
                } else if (wechatSex == 2) {
                    sex = "girl";
                } else {
                    sex = "secret";
                }
                RetrofitUploadFileParameterBuilder.newBuilder().cleanParams();
                Map<String, RequestBody> params = RetrofitUploadFileParameterBuilder.newBuilder()
                        .addParameter("wxUnionId", unionId)
                        .addParameter("wxUserName", wechatNickName)
                        .addParameter("wxHeadImg", wechatHeadImg)
                        .addParameter("task", "wxLogin")
                        .addParameter("verify", MD5Utils.GetMD5Value("sendVerificationDreamSecurityData" + unionId))
                        .addParameter("f", "android")
                        .addParameter("sex", sex)
                        .addParameter("language", "zh_cn")
                        .addParameter("countryCode", "+86")
                        .addParameter("version", DeviceUtils.getVersionName())
                        .bulider();

                return userModel.wechatLogin(params);
            }
        }).compose(TransformUtils.<AnonymousResponseBean>defaultSchedulers()).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<AnonymousResponseBean>() {
            @Override
            public void onSuccess(AnonymousResponseBean response) {
//                if(avasterFile!=null&&avasterFile.exists()){
//                    avasterFile.delete();
//                }
                Constants.WECHAT_LOGIN_CODE = "";
                hideProgress();
                PreferenceUtils.SaveUserId(response.getUserId() + "");
                PreferenceUtils.SaveUserToken(response.getToken());
                if (("y").equals(response.getIsNew())) {
                    Intent intent = new Intent(DeviceRegisterActivity.this, CompleteUserInfoActivity.class);
                    intent.putExtra("key_wechat", true);
                    intent.putExtra("key_wechat_header", avasterFile.getPath());
                    intent.putExtra("key_wechat_nick", wechatNickName);
                    intent.putExtra("key_wechat_sex", wechatSex);
                    startActivity(intent);
                    App.GetInstance().finishActivity(DeviceRegisterActivity.this);
                } else {
                    Intent intent = new Intent(DeviceRegisterActivity.this, MainActivity.class);
                    startActivity(intent);
                    App.GetInstance().finishActivity(DeviceRegisterActivity.this);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                if(avasterFile!=null&&avasterFile.exists()){
                    avasterFile.delete();
                }
                Constants.WECHAT_LOGIN_CODE = "";
                hideProgress();
                ToastUtils.showShortToast(DeviceRegisterActivity.this, response.getDesc());
            }
        });
    }

    @OnClick({ R.id.layout_wechat_login,R.id.layout_phone_login})
    void doClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.layout_wechat_login:
                KeyCounterUtils.SendKeyCounter("0370b8c9a82d4b7197f28d79bd25eb2d");
                wechatLoginin();
                break;
            case R.id.layout_phone_login:
                KeyCounterUtils.SendKeyCounter("02bba5bf148a4309bf14c9a0807ce8ca");
                Intent intent_login = new Intent(DeviceRegisterActivity.this, PhoneLoginActivity.class);
                startActivity(intent_login);
                break;
        }
    }

    private void wechatLoginin() {
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_login_state";
        api.sendReq(req);
    }
}
